/*jslint sloppy: true */
/*global require */
var LM = require('../global');
var hljs = require('highlight.js/lib/highlight.js');
var extend = require('angular').extend;
require('./detail.html');

LM.controller('Case', function ($scope, Case, Project, Token, $routeParams, $sce, $location) {
	var caseForm, $case,
		projectId = $routeParams.projectId;

	caseForm = $scope.caseData = {};
	$case = $scope['case'] = Case.get({
		caseId: $routeParams.caseId,
		projectId: projectId
	}, function () {
		$scope.code = $sce.trustAsHtml(hljs.highlight('lemoncase', $case.code, true).value);
		extend(caseForm, $case);
	});

	$scope.removeCase = function () {
		$case.$remove(null, function () {
			$location.url('/project/' + projectId + '/case');
		});
	};

	$scope.removeCaseEnter = function () {
		if ($scope.deleteWord === 'DELETE') {
			$scope.removeCase();
		}
	};

	$scope.updateCase = function () {
		extend($case, caseForm).$modify();
	};

	$scope.newTag = '';
	$scope.addTag = function () {
		if (!$scope.newTag) {
			return;
		}

		$scope['case'].tags.push($scope.newTag);
		$case.$modify(null, function () {
			$scope.newTag = '';
		});
	};

	$scope.removeTag = function (index) {
		$case.tags.splice(index, 1);
		$case.$modify();
	};

	//init
	$scope.project = Project.get({ projectId: projectId });
	$scope.token = Token.get({ projectId: projectId });

	$scope.queryConfig.clear().setActive();
	$scope.navConfig.setHref('#/project/' + projectId + '/case').setType('back');
});
